//
//  ChildrenStoryController.m
//  HappyBaby
//
//  Created by 华哥 on 15/11/23.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "ChildrenStoryController.h"
#import "VideoPlayer.h"
#import "ChildrenStoryDetail.h"
#import "ChildrenStoryList.h"
#import "Define.h"

#import "ChildrenStoryTableCell.h"
#import "ChildrenStoryCollectCell.h"
#import "EveryTypeController.h"
#import "ChildrenStoryInterfaceCell.h"
#import "SqliteManager.h"
#import "MJRefresh.h"

#import "UserShareController.h"
#import "UserShareListController.h"

/////////////
#import "HBAudioPlayController.h"

#define kChildrenStoryDetailUrl @"http://360web.shoujiduoduo.com/ringweb/bbweb.php?type=getlist&page=0&pagesize=30"
#define kChildrenStoryCollectUrl @"http://360web.shoujiduoduo.com/ringweb/bbweb.php?type=getcate&page=0&pagesize=30"
#define kChildrenStoryInterfaceCollection @"http://bb.shoujiduoduo.com/baby/bb.php?type=getvideos&page=1&pagesize=30&collectid=29"

@interface ChildrenStoryController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UITableView *tableView;
// 顶部collectionView;
@property (nonatomic, strong) UICollectionView *collectionView;
// 详细的collectionView;
@property (nonatomic, strong) UICollectionView *detailCollectionView;
//@property (nonatomic, strong) VideoPlayer *player;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSMutableArray *collectArray;
@property (nonatomic, strong) NSMutableArray *detailArray;
@property (nonatomic, strong) UIButton *unfoldCollectionView;
@property (nonatomic, assign) BOOL isUnfold;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) AVAudioPlayer *avdioPlayer;
@property (nonatomic, assign) NSInteger isPlayModel;
@property (nonatomic, assign) BOOL isPlay;
// 加载刷新时, 控制加载到第几页;
@property (nonatomic, assign) NSInteger page;


@end

static NSString *tableViewCellIndentifier = @"cell";
static NSString *collectViewCellIndentifier = @"collect";
@implementation ChildrenStoryController



- (NSMutableArray *)collectArray
{
    if (_collectArray == nil)
    {
        _collectArray = [NSMutableArray array];
    }
    return _collectArray;
}

- (NSMutableArray *)modelArray
{
    if (_modelArray == nil)
    {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (NSMutableArray *)detailArray
{
    if (_detailArray == nil)
    {
        _detailArray = [NSMutableArray array];
    }
    return _detailArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    
    
    [self analyse];
    [self creatView];
    
//    上拉加载更多方法;
    [self.detailCollectionView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerRefreshing)];
//    下拉刷新方法
    [self.detailCollectionView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerRefreshing)];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithTitle:@"广场" style:UIBarButtonItemStylePlain target:self action:@selector(barButtonAction)];
    self.navigationItem.rightBarButtonItem = barButton;
}
- (void)barButtonAction
{
    UserShareListController *userListVc = [[UserShareListController alloc]init];
    [self.navigationController pushViewController:userListVc animated:YES];
}

- (void)creatView
{
//    DetailCollectionView
    UICollectionViewFlowLayout *detailLayout = [[UICollectionViewFlowLayout alloc]init];
    detailLayout.itemSize = CGSizeMake((kScreenWidth- 50 ) / 2, (kScreenWidth- 50 ) / 2 * 4 / 5);

    self.detailCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(10, 60 * kScreenHeight / 667, kScreenWidth - 20, kScreenHeight - 100 * kScreenHeight / 667) collectionViewLayout:detailLayout];
    [self.detailCollectionView registerClass:[ChildrenStoryInterfaceCell class] forCellWithReuseIdentifier:@"CollectionCell"];
    self.detailCollectionView.backgroundColor = [UIColor whiteColor];
    self.detailCollectionView.delegate = self;
    self.detailCollectionView.dataSource = self;
    [self.view addSubview:_detailCollectionView];
    
//    topCollectionView;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(kScreenWidth / 4, 30 * kScreenHeight / 667);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 60 * kScreenHeight / 667) collectionViewLayout:layout];
    
    self.collectionView.backgroundColor = [UIColor colorWithRed:214.0 / 256.0 green:209.0 / 256.0 blue:214.0 / 256.0 alpha:1];
    [self.collectionView registerClass:[ChildrenStoryCollectCell class] forCellWithReuseIdentifier:collectViewCellIndentifier];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    // 设置collectionView不能滚动;
    self.collectionView.scrollEnabled = NO;
    [self.view addSubview:_collectionView];
    
    
    self.unfoldCollectionView = [UIButton buttonWithType:UIButtonTypeCustom];
    self.unfoldCollectionView.backgroundColor = [UIColor redColor];
    self.unfoldCollectionView.frame = CGRectMake(0, 0, layout.itemSize.width, layout.itemSize.height);
    
//    初始化之前把当前播放的第几首设置成 INT32_MAX;
    self.isPlayModel = INT32_MAX;
    self.avdioPlayer = [[AVAudioPlayer alloc]init];
}



#pragma mark ----------------------- collectionView 设置 ------------------
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.collectionView)
    {
        if (self.collectArray.count == 0)
        {
            return 0;
        }
        else
        {
            return 30;
        }
    }
    else
    {
        if (self.detailArray.count == 0)
        {
            return 0;
        }
        else
        {
            return self.detailArray.count;
        }
    }
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectionView)
    {
        ChildrenStoryCollectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectViewCellIndentifier forIndexPath:indexPath];
        cell.childrenStoryListModel = self.collectArray[indexPath.item + 1];
        if (!_isUnfold)
        {
            if (indexPath.row == 7)
            {
                cell.typeLabel.text = @"更多>>";
                UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
                button.frame = cell.bounds;
                [button addTarget:self action:@selector(unfoldButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:button];
            }
        }
        else
        {
            if (indexPath.row == 23)
            {
                
                UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
                button.frame = CGRectMake(0, 0,kScreenWidth / 5, 30 * kScreenHeight / 667);
                [button addTarget:self action:@selector(unfoldButtonAction1:) forControlEvents:UIControlEventTouchUpInside];
                cell.typeLabel.text = @"收起^";
                [cell addSubview:button];
            }
        }    
        return cell;
    }
    else
    {
        ChildrenStoryInterfaceCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
        cell.playAndPausebutton.tag = indexPath.row;
        cell.model = self.detailArray[indexPath.row];
        if (_isPlayModel != INT32_MAX)
        {
            if (indexPath.row == _isPlayModel)
            {
                cell.thcircularProgress.hidden = NO;
                if (self.avdioPlayer != NULL)
                {
                    if (self.avdioPlayer.isPlaying)
                    {
                        [cell.playAndPausebutton setImage:[UIImage imageNamed:@"pauseVideo"] forState:UIControlStateNormal];
                    }
                    else
                    {
                        [cell.playAndPausebutton setImage:[UIImage imageNamed:@"plyayVideo"] forState:UIControlStateNormal];
                    }
                }
            }
            else
            {
                cell.thcircularProgress.hidden = YES;
                [cell.playAndPausebutton setImage:[UIImage imageNamed:@"iconfont-erji"] forState:UIControlStateNormal];
            }
        }
        
        cell.backgroundColor = [UIColor whiteColor];
        return cell;
    }
}

// 点击collectionView执行方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectionView)
    {
        // 点击上面的collectionView实现跳转功能;
        ChildrenStoryList *model = self.collectArray[indexPath.row + 1];
        NSString *string = [NSString stringWithFormat:@"http://bb.shoujiduoduo.com/baby/bb.php?type=getlist&page=0&pagesize=30&listid=%@",model.myID];
        EveryTypeController *everyVc = [[EveryTypeController alloc]init];
        everyVc.url = string;
        everyVc.listModel = model;
        
        ChildrenStoryInterfaceCell *detailcell = (ChildrenStoryInterfaceCell *)[self.detailCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:_isPlayModel inSection:0]];
        [detailcell.playAndPausebutton setImage:[UIImage imageNamed:@"iconfont-erji"] forState:UIControlStateNormal];
        detailcell.thcircularProgress.hidden = YES;
        self.avdioPlayer = nil;
        [self.avdioPlayer stop];
        [self.timer invalidate];

        [self.navigationController pushViewController:everyVc animated:YES];
    }
    else
    {
        //////////////////////////修改功能在详细播放界面播放音乐
        self.hidesBottomBarWhenPushed = YES;
        
        HBAudioPlayController *audioPlayerVc = [[HBAudioPlayController alloc]init];
        // 传值到第二界面
        audioPlayerVc.musicArray = self.detailArray;
        audioPlayerVc.playIndex = indexPath.row;
        [self.navigationController pushViewController:audioPlayerVc animated:YES];
    }
}


- (void)playWithModel:(ChildrenStoryInterface *)model
{
    SqliteManager *sql = [SqliteManager shareInstance];
    ChildrenStoryInterface *childmodel = [sql selectOneDataWithTableName:@"HappyBaby" downurl:model.downurl];
    if (childmodel)
    {
        NSURL *fileURL = [NSURL fileURLWithPath:childmodel.savePath];
        self.avdioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
        [self.avdioPlayer play];
        //    添加一个定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    else
    {
        NSURL *url = [NSURL URLWithString:model.downurl];
        NSData *data = [NSData dataWithContentsOfURL:url];
        //    将数据保存到本地
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@.mp4",docPath,model.name];
        model.savePath = filePath;
        [data writeToFile:filePath atomically:YES];
        //    播放本地音乐
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];
        
        self.avdioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
        [self.avdioPlayer play];
        [sql creatTableWithTableName:@"HappyBaby"];
        [sql insertDataWithTableName:@"HappyBaby" childrenStoryDetail:model];
        //    添加一个定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }    
}

#pragma mark ------------------------ 进度条相关 ------------------------
- (void)timerAction
{
    ChildrenStoryInterfaceCell *cell = (ChildrenStoryInterfaceCell *)[self.detailCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:_isPlayModel inSection:0]];
    cell.thcircularProgress.percentage = self.avdioPlayer.currentTime / self.avdioPlayer.duration;
    if (self.avdioPlayer.duration - self.avdioPlayer.currentTime < 1)
    {
        ChildrenStoryInterfaceCell *cell = (ChildrenStoryInterfaceCell *)[self.detailCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:_isPlayModel inSection:0]];
        cell.thcircularProgress.hidden = YES;
        [cell.playAndPausebutton setImage:[UIImage imageNamed:@"iconfont-erji"] forState:UIControlStateNormal];
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (collectionView == self.detailCollectionView)
    {
        return UIEdgeInsetsMake(0, 5, 5, 5);
    }
    else
        return UIEdgeInsetsMake(0, 0, 0, 0);
}

#pragma mark --------------------- 点击展开按钮执行的方法 -------------------------
- (void)unfoldButtonAction:(UIButton *)button
{
    [button removeFromSuperview];
    [UIView animateWithDuration:0.5 animations:^{
        self.collectionView.frame = CGRectMake(0, 0, kScreenWidth, 180 * kScreenHeight / 667);
        _isUnfold = !_isUnfold;
        [self.collectionView reloadData];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)unfoldButtonAction1:(UIButton *)button
{
    [button removeFromSuperview];
    [UIView animateWithDuration:0.5 animations:^{
        self.collectionView.frame = CGRectMake(0, 0, kScreenWidth, 60 * kScreenHeight / 667);
        _isUnfold = !_isUnfold;
        [self.collectionView reloadData];
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark ----------------------- 解析数据 -----------------------------
- (void)analyse
{
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:@"http://bb.shoujiduoduo.com/baby/bb.php?type=getlist&page=0&pagesize=30&listid=5"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *array = [dic objectForKey:@"nav"];
        for (int i = 1; i < array.count; i++)
        {
            NSDictionary *dic = array[i];
            ChildrenStoryList *model = [[ChildrenStoryList alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.collectArray addObject:model];

        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
    }]resume];
    
    
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:kChildrenStoryInterfaceCollection] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *firstDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *array = [firstDic objectForKey:@"list"];
        for (int i = 1; i < array.count - 1; i++)
        {
            NSDictionary *dic = array[i];
            ChildrenStoryInterface *model = [[ChildrenStoryInterface alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.detailArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.detailCollectionView reloadData];
            self.page = 1;
        });
    }]resume];
}

#pragma mark --------------------- 加载 / 刷新的执行方法 ------------
- (void)footerRefreshing
{
    NSString *url = [NSString stringWithFormat:@"http://bb.shoujiduoduo.com/baby/bb.php?type=getvideos&page=%ld&pagesize=30&collectid=29",(long)self.page];
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *firstDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *array = [firstDic objectForKey:@"list"];
        for (int i = 1; i < array.count - 1; i++)
        {
            NSDictionary *dic = array[i];
            ChildrenStoryInterface *model = [[ChildrenStoryInterface alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.detailArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.detailCollectionView reloadData];
            [self.detailCollectionView.footer endRefreshing];
            self.page += 1;
        });
    }]resume];
}

- (void)headerRefreshing
{
    [self performSelector:@selector(headerRefreshingEnd) withObject:nil afterDelay:1];
}
- (void)headerRefreshingEnd
{
    [self.detailCollectionView.header endRefreshing];
}


@end
